package com.scut.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scut.campus.context.BaseContext;
import com.scut.campus.dto.PageDTO;
import com.scut.campus.dto.TradeUpdateDto;
import com.scut.campus.entity.Trade;
import com.scut.campus.mapper.TradeMapper;
import com.scut.campus.query.MainTradeQuery;
import com.scut.campus.query.TradeQuery;
import com.scut.campus.service.TradeService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade> implements TradeService {
    @Autowired
    private TradeMapper tradeMapper;

    @Override
    public PageDTO<Trade> queryMyTrade(TradeQuery tradeQuery) {


        Page<Trade> page = tradeQuery.toMpPageDefaultSortByCreateTimeDesc();

        LambdaQueryWrapper<Trade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Trade::getUserId, BaseContext.getCurrentId());
        page(page, queryWrapper);
        return PageDTO.of(page, Trade.class);
    }

    @Override
    public PageDTO<Trade> queryMainTrade(MainTradeQuery mainTradeQuery) {
        Page<Trade> page = mainTradeQuery.toMpPageDefaultSortByCreateTimeDesc();


        LambdaQueryWrapper<Trade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Objects.nonNull(mainTradeQuery.getMinPrice()), Trade::getPrice, mainTradeQuery.getMinPrice())
                .le(Objects.nonNull(mainTradeQuery.getMaxPrice()), Trade::getPrice, mainTradeQuery.getMaxPrice())
                .eq(Objects.nonNull(mainTradeQuery.getType()), Trade::getType, mainTradeQuery.getType())
                .eq(Strings.isNotBlank(mainTradeQuery.getBuildings()), Trade::getBuildings, mainTradeQuery.getBuildings())
                .eq(Objects.nonNull(mainTradeQuery.getArea()), Trade::getArea, mainTradeQuery.getArea());
        page(page, queryWrapper);

        return PageDTO.of(page, Trade.class);

    }

    @Override
    public void updateTrade(TradeUpdateDto tradeUpdateDto) {
        Trade trade = new Trade();
        BeanUtils.copyProperties(tradeUpdateDto, trade);

        trade.setUserId(BaseContext.getCurrentId());

        this.updateById(trade);
    }
}
